package com.sjl.config.shiro;

import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import com.alibaba.dubbo.config.annotation.Reference;
import com.sjl.springboot.domain.user.SysUser;
import com.sjl.springboot.inface.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author  sjl
 * @version V1.0
 * @Package com.sjl.config.shiro
 * @Date 2019年01月22日10:44:25
 * @
 */
public class MyShiroRealm extends AuthorizingRealm {

    private static Log log = StaticLog.get();

    @Reference
    private UserService userService;

    /**
     * 用户授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1.获取用户
        //2.获取用户角色
        //3.获取用户权限
        return null;
    }

    /**
     * 用户身份验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token  = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        SysUser user = null;
        try {
            user = userService.getUserByName(username).getResult();

            if(user==null||!StringUtils.equals(user.getPassword(),new Md5Hash(username + password + user.getSalt()).toHex())){
                throw new Exception("账号或密码不正确");
            }
        } catch (Exception e) {
            log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage());
            throw new AuthenticationException(e.getMessage(), e);
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }


}
